<template>
  <!-- 商品添加 -->
  <div class="p-2">
    <el-card>
      <template v-slot:header>
        <div class="muonseu">
          <div class="clearfix">
            <span>{{ title }}</span>
          </div>
          <div>
            <el-button type="primary" @click="submitForm">提 交</el-button>
            <el-button type="danger" @click="close">关 闭</el-button>
          </div>
        </div>
      </template>
      <el-form ref="goodsFormRef" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="8">
<!--            <el-form-item label="商品编号" prop="nasnme">-->
<!--              <el-input v-model.trim="form.sn" clearable placeholder="请输入" style="width: 300px;" />-->
<!--            </el-form-item>-->
            <el-form-item label="商品名称" prop="name">
              <el-input v-model.trim="form.name" clearable placeholder="请输入" maxlength="100" style="width: 300px;" />
            </el-form-item>
            <el-form-item label="App" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择" clearable :disabled="disabledType">
                <el-option v-for="item in supplier" :key="item.merchantCode" :label="item.name" :value="item.merchantCode" />
              </el-select>
            </el-form-item>
            <el-form-item label="售价/元" prop="price">
              <el-input-number v-model="form.price" placeholder="请输入" controls-position="right" :min="0" :precision="2"
                               :step="0.01" style="width: 200px;" @blur="blurValidator" />
            </el-form-item>
<!--            <el-form-item label="显示位置" prop="type">-->
<!--              <el-select v-model="form.type" placeholder="请选择" clearable :disabled="disabledType">-->
<!--                <el-option label="批发区" value="WHOLESALE" />-->
<!--                <el-option label="寄卖区" value="CONSIGN" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->

<!--            <el-form-item label="仓库" prop="warehouseCode">-->
<!--              <el-select v-model="form.warehouseCode" clearable :disabled="disabledType" placeholder="请选择">-->
<!--                <el-option v-for="dict in warehose_code" :key="dict.value" :label="dict.label" :value="dict.value" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
          </el-col>
          <el-col :span="8" class="numSty">
            <el-form-item label="商品类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择" clearable style="width: 90px">
                <el-option label="月会员" value="MONTH" />
                <el-option label="年会员" value="YEAR" />
                <el-option label="永久会员" value="PERMANENT" />
              </el-select>
            </el-form-item>
            <el-form-item label="排序" prop="sortNum">
              <el-input-number v-model="form.sortNum" placeholder="请输入" controls-position="right" :max="99999999" :min="0"
                :precision="0" style="width: 200px;" />
            </el-form-item>
<!--            <el-form-item label="库存" prop="stock">-->
<!--              <el-input-number v-model="form.stock" placeholder="请输入" controls-position="right" :min="0" :precision="0"-->
<!--                style="width: 200px;" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="划线价/元" prop="marketPrice">-->
<!--              <el-input-number v-model="form.marketPrice" placeholder="请输入" controls-position="right" :min="0"-->
<!--                :precision="2" :step="0.01" style="width: 200px;" @blur="blurValidator" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="售价/元" prop="price">-->
<!--              <el-input-number v-model="form.price" placeholder="请输入" controls-position="right" :min="0" :precision="2"-->
<!--                :step="0.01" style="width: 200px;" @blur="blurValidator" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="成本价/元" prop="cost">-->
<!--              <el-input-number v-model="form.cost" placeholder="请输入" controls-position="right" :min="0" :precision="2"-->
<!--                :step="0.01" style="width: 200px;" @blur="blurValidator" />-->
<!--            </el-form-item>-->
          </el-col>
<!--          <el-col :span="8" class="numSty">-->
<!--            <el-form-item label="寄卖返佣/元" prop="saleRebate">-->
<!--              <el-input-number v-model="form.saleRebate" placeholder="请输入" controls-position="right" :min="0"-->
<!--                :precision="2" :step="0.01" style="width: 200px;" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="买手直推反佣/元" prop="directBuyerRebate">-->
<!--              <el-input-number v-model="form.directBuyerRebate" placeholder="请输入" controls-position="right" :min="0"-->
<!--                :precision="2" :step="0.01" style="width: 200px;" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="买手间推返佣/元" prop="indirectBuyerRebate">-->
<!--              <el-input-number v-model="form.indirectBuyerRebate" placeholder="请输入" controls-position="right" :min="0"-->
<!--                :precision="2" :step="0.01" style="width: 200px;" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="卖手直推反佣/元" prop="directSellerRebate">-->
<!--              <el-input-number v-model="form.directSellerRebate" placeholder="请输入" controls-position="right" :min="0"-->
<!--                :precision="2" :step="0.01" style="width: 200px;" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="卖手间推反佣/元" prop="indirectSellerRebate">-->
<!--              <el-input-number v-model="form.indirectSellerRebate" placeholder="请输入" controls-position="right" :min="0"-->
<!--                :precision="2" :step="0.01" style="width: 200px;" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="4">-->
<!--            <el-form-item label="封面" prop="cover">-->
<!--              <el-upload class="avatar-uploader" :action="huonseom.url" :headers="huonseom.headers"-->
<!--                :show-file-list="false" :on-success="coverRequest">-->
<!--                <img v-if="form.cover" :src="form.cover" class="avatar" />-->
<!--                <el-icon v-else class="avatar-uploader-icon">-->
<!--                  <Plus />-->
<!--                </el-icon>-->
<!--              </el-upload>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="4">-->
<!--            <el-form-item label="小图" prop="smallPic">-->
<!--              <el-upload class="avatar-uploader" :action="huonseom.url" :headers="huonseom.headers"-->
<!--                :show-file-list="false" :on-success="smallPicRequest">-->
<!--                <img v-if="form.smallPic" :src="form.smallPic" class="avatar" />-->
<!--                <el-icon v-else class="avatar-uploader-icon">-->
<!--                  <Plus />-->
<!--                </el-icon>-->
<!--              </el-upload>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="14">-->
<!--            <el-form-item label="组合商品">-->
<!--              <el-col :span="24">-->
<!--                <el-button type="primary" plain @click="getCompose()" icon="Plus"-->
<!--                  style="margin-bottom: 10px">添加组合商品</el-button>-->
<!--              </el-col>-->
<!--              <el-table :data="form.composeList" v-if="form.composeList.length" max-height="250" border>-->
<!--                &lt;!&ndash; <el-table-column label="组合商品Id" prop="composeId" :show-overflow-tooltip="true" align="center" width="" /> &ndash;&gt;-->
<!--                <el-table-column label="组合商品Sn" prop="sn" :show-overflow-tooltip="true" align="center" width="150" />-->
<!--                <el-table-column label="组合商品名称" prop="name" :show-overflow-tooltip="true" align="center" width="" />-->
<!--                <el-table-column label="组合商品数量" prop="count" align="center" width="150">-->
<!--                  <template #default="scope">-->
<!--                    <el-form ref="rowRef" :model="scope.row" :rules="refRules" label-width="120px">-->
<!--                      <el-form-item label="" prop="count">-->
<!--                        <el-input-number v-model="scope.row.count" :min="1" />-->
<!--                      </el-form-item>-->
<!--                    </el-form>-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column fixed="right" label="操作" align="center" width="100">-->
<!--                  <template #default="scope">-->
<!--                    <el-tooltip content="删除" placement="top">-->
<!--                      <el-button link type="primary" icon="Delete" @click="delCompose(scope.row)"></el-button>-->
<!--                    </el-tooltip>-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--              </el-table>-->
<!--              <el-dialog :title="dialog.title" v-model="dialog.visible" append-to-body>-->
<!--                &lt;!&ndash; 搜索组合商品 &ndash;&gt;-->
<!--                <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">-->
<!--                  <el-form-item label="商品名称" prop="name">-->
<!--                    <el-input v-model.trim="queryParams.name" placeholder="商品名称" clearable style="width: 200px" />-->
<!--                  </el-form-item>-->
<!--                  <el-form-item label="商品编号" prop="sn">-->
<!--                    <el-input v-model.trim="queryParams.sn" placeholder="商品名称" clearable style="width: 200px" />-->
<!--                  </el-form-item>-->
<!--                  <el-form-item>-->
<!--                    <el-button type="primary" @click="handleQuery" icon="Search"-->
<!--                      v-hasPermi="['gms:goods:query']">搜索</el-button>-->
<!--                    <el-button @click="resetQuery" icon="Refresh">重置</el-button>-->
<!--                  </el-form-item>-->
<!--                </el-form>-->
<!--                &lt;!&ndash; 列表 &ndash;&gt;-->
<!--                <el-table ref="supTableRef" v-loading="loading" :data="goodsListl" border>-->
<!--                  <el-table-column label="商品编号" prop="sn" align="center" width="" />-->
<!--                  <el-table-column label="商品名称" prop="name" align="center" width="" />-->
<!--                  <el-table-column label="库存" prop="stock" align="center" width="" />-->
<!--                  <el-table-column fixed="right" label="操作" align="center" width="100">-->
<!--                    <template #default="scope">-->
<!--                      <el-tooltip content="添加为组合商品" placement="top">-->
<!--                        <el-button link type="primary" icon="TopRight" @click="addCompose(scope.row)"></el-button>-->
<!--                      </el-tooltip>-->
<!--                    </template>-->
<!--                  </el-table-column>-->
<!--                </el-table>-->
<!--                <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"-->
<!--                  v-model:limit="queryParams.pageSize" @pagination="getList" />-->
<!--              </el-dialog>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="24">-->
<!--            <el-form-item label="商品详情图">-->
<!--              <template #label>-->
<!--                <div style="display: flex; flex-wrap: wrap; justify-content: flex-end">-->
<!--                  <div>商品详情图</div>-->
<!--                  <el-button v-if="!introSort.length" type="primary" @click="introFn">排 序</el-button>-->
<!--                  <el-button v-if="introSort.length" type="primary" @click="introConfirm" style="margin-bottom: 8px;">确-->
<!--                    认</el-button>-->
<!--                  <el-button v-if="introSort.length" @click="introCancellation">取 消</el-button>-->
<!--                </div>-->
<!--              </template>-->
<!--              <div v-if="!introSort.length">-->
<!--                <el-upload :file-list="introList" :action="huonseom.url" :headers="huonseom.headers"-->
<!--                  list-type="picture-card" :on-success="introRequest" :on-preview="introPreview">-->
<!--                  <el-icon>-->
<!--                    <Plus />-->
<!--                  </el-icon>-->
<!--                </el-upload>-->
<!--                <el-dialog v-model="introVisible" width="500px">-->
<!--                  <img w-full :src="introUrl" alt="" />-->
<!--                </el-dialog>-->
<!--              </div>-->
<!--              <draggable :list="introSort" animation="300" item-key="id" style="display: flex;flex-wrap: wrap;">-->
<!--                <template #item="{ element }">-->
<!--                  <div class="item">-->
<!--                    <el-image style="width: 146px; height: 146px; margin-right: 10px;"-->
<!--                      :src="element.url " fit="contain" />-->
<!--                  </div>-->
<!--                </template>-->
<!--              </draggable>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="24">-->
<!--            <el-form-item label="商品轮播图">-->
<!--              <template #label>-->
<!--                <div style="display: flex; flex-wrap: wrap; justify-content: flex-end">-->
<!--                  <div>商品轮播图</div>-->
<!--                  <el-button v-if="!imagesSort.length" type="primary" @click="imagesFn">排 序</el-button>-->
<!--                  <el-button v-if="imagesSort.length" type="primary" @click="imagesConfirm" style="margin-bottom: 8px;">确-->
<!--                    认</el-button>-->
<!--                  <el-button v-if="imagesSort.length" @click="imagesCancellation">取 消</el-button>-->
<!--                </div>-->
<!--              </template>-->
<!--              <div v-if="!imagesSort.length">-->
<!--                <el-upload :file-list="imagesList" :action="huonseom.url" :headers="huonseom.headers"-->
<!--                  list-type="picture-card" :on-success="imagesRequest" :on-preview="imagesPreview">-->
<!--                  <el-icon>-->
<!--                    <Plus />-->
<!--                  </el-icon>-->
<!--                </el-upload>-->
<!--                <el-dialog v-model="imagesVisible" width="500px">-->
<!--                  <img w-full :src="imagesUrl" alt="" />-->
<!--                </el-dialog>-->
<!--              </div>-->
<!--              <draggable :list="imagesSort" animation="300" item-key="id" style="display: flex;flex-wrap: wrap;">-->
<!--                <template #item="{ element }">-->
<!--                  <div class="item">-->
<!--                    <el-image style="width: 146px; height: 146px; margin-right: 10px;"-->
<!--                      :src="element.url " fit="contain" />-->
<!--                  </div>-->
<!--                </template>-->
<!--              </draggable>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>

        <!-- <el-form-item>
          <el-button type="primary" @click="submitForm">提 交</el-button>
          <el-button type="danger" @click="close">关 闭</el-button>
        </el-form-item> -->
      </el-form>
    </el-card>
  </div>
</template>
<script setup lang="ts" name="AddGoods">
import upload from "@/utils/upload";
import { listValidSupplier } from '@/api/system/supplier/index';
import { SupVO } from '@/api/system/supplier/types';
import { listGoods, addGoods, getGoods, updateGoods } from '@/api/operates/goods/index';
import { GoodsQuery, GoodsVO, GoodsForm } from '@/api/operates/goods/types';
// 获取toke的方法
import { globalHeaders } from "@/utils/request";

const router = useRouter();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { warehose_code } = toRefs<any>(proxy?.useDict('warehose_code'));
const huonseom = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/file/upload'
})

// // 获取实例
// const route = useRoute()
// // 解构赋值
// const { query: { type, id } } = route

// 接收父组件的参数
const { id } = defineProps({
  id: {}
});

// 顶部标题
const title = ref<string>('')

const disabledType = ref(false)

// 供应商列表
const supplier = ref<SupVO[]>()

const goodsFormRef = ref<ElFormInstance>()
const queryFormRef = ref<ElFormInstance>()
const rowRef = ref<ElFormInstance>()

//详情图
const introList = ref<any>([])
const introUrl = ref('')
const introVisible = ref(false)
const introSort = ref<any>([])

// 轮播图
const imagesList = ref<any>([])
const imagesUrl = ref('')
const imagesVisible = ref(false)
const imagesSort = ref<any>([])

// 划线价 > 售价 > 成本价
// 成本价 >= 销售价的70%
// 划线价校验
const marketPriceValidator = (rule: any, value: number, callback: any) => {
  if (value === 0) {
    callback(new Error("划线价不能为0"));
  } else {
    callback();
  }
};
// 售价校验
const priceValidator = (rule: any, value: number, callback: any) => {
  if (value === 0) {
    callback(new Error("售价不能为0"));
  } else if (form.value.marketPrice && value >= form.value.marketPrice) {
    callback(new Error("售价必须小于划线价"));
  } else {
    callback();
  }
};
// 成本价校验
const costValidator = (rule: any, value: number, callback: any) => {
  if (value === 0) {
    callback(new Error("成本价不能为0"));
  } else if (form.value.price && value >= form.value.price) {
    callback(new Error("成本价必须小于售价"));
  } else if (form.value.price && value < form.value.price * 0.7) {
    callback(new Error("成本价必须大于等于售价的70%"));
  } else {
    callback();
  }
};
// 联动校验
const blurValidator = async () => {
  const obj: { [key: string]: any } = { ...form.value }
  const arr = ['marketPrice', 'price', 'cost']
  arr.forEach(item => {
    if (obj[item]) goodsFormRef.value?.validateField(item, () => null)
  })
};

const initForm: GoodsForm = {
  sn: '',
  type: '',
  name: '',
  intro: '',
  cover: '',
  smallPic: '',
  images: '',
  warehouseCode: '',
  composeList: []
}

const data = reactive<PageData<GoodsForm, GoodsQuery>>({
  form: { ...initForm },
  queryParams: {
    name: '',
    sn: '',
    compose: 0,
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
    type: [{ required: true, message: "请选择显示位置", trigger: "change" }],
    supplierId: [{ required: true, message: "请选择供应商", trigger: "change" }],
    warehouseCode: [{ required: true, message: "请选择仓库", trigger: "change" }],
    cover: [{ required: true, message: "请添加封面", trigger: "change" }],
    smallPic: [{ required: true, message: "请添加小图", trigger: "change" }],
    stock: [
      { required: true, message: "请输入库存", trigger: "blur" },
      { pattern: /^[1-9]\d*$/, message: "必须为正整数", trigger: "blur" },
    ],
    marketPrice: [
      { required: true, message: "请输入划线价", trigger: "blur" },
      { pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: "必须为数字，且至多两位小数", trigger: "blur" },
      { validator: marketPriceValidator, trigger: "blur" }
    ],
    price: [
      { required: true, message: "请输入售价", trigger: "blur" },
      { pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: "必须为数字，且至多两位小数", trigger: "blur" },
      { validator: priceValidator, trigger: "blur" }
    ],
    cost: [
      { required: true, message: "请输入成本价", trigger: "blur" },
      { pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: "必须为数字，且至多两位小数", trigger: "blur" },
      { validator: costValidator, trigger: "blur" }
    ],
    saleRebate: [
      { required: true, message: "请输入寄卖返佣", trigger: "blur" },
      { pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: "必须为数字，且至多两位小数", trigger: "blur" },
    ],
    directBuyerRebate: [
      { required: true, message: "请输入买手直推反佣", trigger: "blur" },
      { pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: "必须为数字，且至多两位小数", trigger: "blur" },
    ],
    indirectBuyerRebate: [
      { required: true, message: "请输入买手间推返佣", trigger: "blur" },
      { pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: "必须为数字，且至多两位小数", trigger: "blur" },
    ],
    directSellerRebate: [
      { required: true, message: "请输入卖手直推反佣", trigger: "blur" },
      { pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: "必须为数字，且至多两位小数", trigger: "blur" },
    ],
    indirectSellerRebate: [
      { required: true, message: "请输入卖手间推反佣", trigger: "blur" },
      { pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: "必须为数字，且至多两位小数", trigger: "blur" },
    ],
  }
})

const { form, queryParams, rules } = toRefs(data)

const refRules = {
  count: { required: true, message: "组合商品数量不能为空", trigger: "blur" },
}

// 组合商品
const goodsListl = ref<GoodsVO[]>([]);
const loading = ref(true)
const total = ref(0)

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const getTitle = () => {
  if (id) {
    title.value = '商品修改'
    disabledType.value = true
  } else {
    title.value = '商品添加'
  }
}

/**
 * 获取封面url
 * @param res
 */
const coverRequest = async (res: any) => {
  // const res = await upload(op.file);
  // form.value.cover = res
  if (res.code === 200) {
    // form.value.cover = res.data.url;
    form.value.cover = res.data.url.replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com');
    console.log(form.value.cover);
  } else {
    proxy?.$modal.loading(res.msg);
  }
}

/**
 * 获取小图
 * @param res
 */
const smallPicRequest = async (res: any) => {
  // const res = await upload(op.file);
  // form.value.smallPic = res
  if (res.code === 200) {
    form.value.smallPic = res.data.url.replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com');
  } else {
    proxy?.$modal.loading(res.msg);
  }
}

/**
 * 获取详情图
 * @param res
 */
const introRequest = async (res: any) => {
  // const res = await upload(op.file);
  // introList.value.push({ url: res });
  if (res.code === 200) {
    const introUrl = res.data.url.replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com')
    introList.value.push({ url: introUrl });
  } else {
    proxy?.$modal.loading(res.msg);
  }
}
const introPreview = (op: any) => {
  introUrl.value = op.url
  introVisible.value = true
}
// 排序
const introFn = () => {
  introSort.value = [...introList.value]
}
// 确认排序
const introConfirm = () => {
  introList.value = [...introSort.value]
  introSort.value = []
}
// 取消排序
const introCancellation = () => {
  introSort.value = []
}

/**
 * 轮播图
 * @param res
 */
const imagesRequest = async (res: any) => {
  // const res = await upload(op.file);
  // imagesList.value.push({ url: res });
  if (res.code === 200) {
    const imagesUrl = res.data.url.replace('juguanghe.oss-cn-hangzhou.aliyuncs.com', 'oss.fengjuhe.com')
    imagesList.value.push({ url: imagesUrl });
  } else {
    proxy?.$modal.loading(res.msg);
  }
}
const imagesPreview = (op: any) => {
  introUrl.value = op.url
  introVisible.value = true
}
// 排序
const imagesFn = () => {
  imagesSort.value = [...imagesList.value]
}
// 确认排序
const imagesConfirm = () => {
  imagesList.value = [...imagesSort.value]
  imagesSort.value = []
}
// 取消排序
const imagesCancellation = () => {
  imagesSort.value = []
}

// /**
//  * 显示组合商品弹框
//  */
const getCompose = () => {
  dialog.visible = true;
  dialog.title = "添加组合商品";
  handleQuery()
}

/**
 * 删除组合组合商品
 * @param row
 */
const delCompose = (row: any) => {
  form.value.composeList = form.value.composeList.filter(item => {
    return item.sn != row.sn
  })
}

/**
 * 商品修改时获取轮播图和详情图
 */
const getGoodsInfo = async () => {
  if (id) {
    const { data } = await getGoods(id as string | number)

    const res: { [key: string]: any } = data
    const formKeys = ['marketPrice', 'price', 'cost', 'saleRebate', 'directBuyerRebate', 'indirectBuyerRebate', 'directSellerRebate', 'indirectSellerRebate']
    // 编辑时价格和返佣字符串转化为数字
    formKeys.forEach((item: string) => {
      res[item] = res[item] * 1
    })
    form.value = res as GoodsForm
    // 轮播图和详情图编辑时转化为数组
    form.value.intro.split(",").forEach((item) => {
      if (item) introList.value.push({ url: item });
    });
    form.value.images.split(",").forEach((item) => {
      if (item) imagesList.value.push({ url: item });
    });
  }
}

/**
 * 添加组合商品时获取商品列表
 */
const getList = async () => {
  loading.value = true
  const res = await listGoods(queryParams.value);
  goodsListl.value = res.data.list;
  total.value = res.data.total;
  loading.value = false;
}
/**
 * 搜索组合商品
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}
/**
 * 重置搜索
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/**
 * 添加组合商品
 * @param row
 */
const addCompose = (row: GoodsVO) => {
  let lag = form.value.composeList.some(item => item.sn == row.sn)
  if (!lag) {
    form.value.composeList.push(
      {
        sn: row.sn,
        name: row.name,
        count: 1,
      }
    )
    dialog.visible = false
  } else {
    proxy?.$modal.msgError("已存在该组合商品")
  }
}


/**
 * 提交
 */
const submitForm = async () => {
  try {
    // 详情图
    const arrIntro: any = [];
    introList.value.forEach((item: any) => arrIntro.push(item.url))
    form.value.intro = arrIntro.join(",");
    // 轮播图
    const arrImg: any = [];
    imagesList.value.forEach((item: any) => arrImg.push(item.url))
    form.value.images = arrImg.join(",");
    await goodsFormRef.value?.validate()
    let lag = true
    await rowRef.value?.validate((valid: boolean) => {
      if (!valid) {
        proxy?.$modal.msgError("组合商品数量不能为空")
      }
      lag = valid
    })
    if (!lag) return
    id ? await updateGoods(form.value) : await addGoods(form.value)
    proxy?.$modal.msgSuccess(`${id ? '修改' : '添加'}成功`)
    close()
  } catch (error) {

  }
}

/**
 * 关闭
 */
const close = () => {
  proxy?.$tab.closeOpenPage();
  router.push({ name: "Goods" });
}

/**
 * 获取供货商列表
 */
const getSupplier = async () => {
  const res = await listValidSupplier()
  supplier.value = res.data
}

onMounted(() => {
  getSupplier()
  getTitle()
  getGoodsInfo()
});

</script>
<style scoped>
.muonseu {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.avatar-uploader .avatar {
  width: 146px;
  height: 146px;
  display: block;
  object-fit: contain;
}

:deep(.numSty .el-input-number .el-input__inner) {
  text-align: left;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 146px;
  height: 146px;
  text-align: center;
}
</style>
